package com.xhsj.user.sms.purchase.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.sms.process.service.TbPurchaseProcessOpinionService;
import com.xhsj.user.sms.process.service.TbPurchaseProcessTaskService;
import com.xhsj.user.sms.purchase.service.*;
import com.xhsj.user.sms.purchase.vo.*;
import com.xhsj.user.sms.purchase.entity.TbPurchaseApply;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseApplyMapper;
import com.xhsj.user.sms.purchase.query.FindRunTaskListQuery;
import com.xhsj.user.sms.purchase.query.PurchaseApplyQuery;
import com.xhsj.user.sms.transfer.entity.TbTaskTransfer;
import com.xhsj.user.sms.transfer.service.TbTaskTransferService;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 采购申请表 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-04-13
 */
@Slf4j
@Api(tags = "采购申请表")
@RestController
@RequestMapping("/purchase/tbPurchaseApply")
public class TbPurchaseApplyController {

    @Autowired
    public TbPurchaseApplyService service;
    @Autowired
    private TbPurchaseApplyMapper tbPurchaseApplyMapper;
    @Autowired
    public TbPurchaseProcessTaskService tbPurchaseProcessTaskService;
    @Autowired
    public TbPurchaseOrderFileService tbPurchaseOrderFileService;
    @Autowired
    public TbPurchaseSubtaskOtherFileService tbPurchaseSubtaskOtherFileService;
    @Autowired
    public TbPurchaseSubtaskPaymentRecordService tbPurchaseSubtaskPaymentRecordService;
    @Autowired
    public TbPurchaseSubtaskPaymentApplyService tbPurchaseSubtaskPaymentApplyService;
    @Autowired
    public TbPurchaseSubtaskQualityRecordService tbPurchaseSubtaskQualityRecordService;
    @Autowired
    public TbPurchaseOrderGoodsService tbPurchaseOrderGoodsService;
    @Autowired
    public TbPurchaseProcessOpinionService tbPurchaseProcessOpinionService;
    @Autowired
    public TbPurchaseTerminationContractApplyFileService tbPurchaseTerminationContractApplyFileService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;
    @Autowired
    private TbGlobalUserService tbGlobalUserService;
    @Autowired
    private TbPurchaseSubtaskListService tbPurchaseSubtaskListService;
    @Autowired
    private TbPurchaseSubtaskStorageRecordFileService tbPurchaseSubtaskStorageRecordFileService;
    @Autowired
    private TbTaskTransferService tbTaskTransferService;

    @Value("${rolekeyname.purchaseSpecialist}")
    private String purchaseSpecialist;

    // 出纳
    @Value("${rolekeyname.teller}")
    private String teller;

//    @ApiOperation(value = "开始流程", notes = "开始流程")
//    @RequestMapping(value = "/startProcess", method = RequestMethod.POST)
//    public Message startProcess(@RequestBody TbPurchaseApply data) {
//        try {
//            data.setAuditStatus("0");
//            data.setSubmitStatus(2);
//            service.startProcess(data);
//            return Message.success("保存成功");
//        } catch (Exception e) {
//            log.error("保存失败:{}", e);
//            return Message.error(1, "保存失败");
//        }
//    }

    @ApiOperation(value = "查询采购模块个人任务待转入转出列表", notes = "查询采购模块个人任务待转入转出列表")
    @RequestMapping(value = "/findPurchaseList", method = RequestMethod.POST)
    public Message findPurchaseList(@RequestBody Map<String, Object> data) {

        Object transFerType = data.get("transFerType");
        if (StringUtils.isBlank(transFerType)) {// 转出
            IPage<Map<String,Object>> selectPage = service.findPurchaseList(data);
            return Message.success("", selectPage.getRecords(), selectPage.getTotal());
        }

        if ("1".equals(String.valueOf(transFerType))) {// 转入
            String type = String.valueOf(data.get("type")); // 1 采购申请 2 采购订单
            if ("1".equals(type)) { // 采购申请
                Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 0, "purchase_apply");
                return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
            } else { // 订单子任务
                Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 0, "order_apply");
                return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
            }
        }
        return Message.success("", null);

    }


    @ApiOperation(value = "查询采购模块审核任务待转出转入列表", notes = "查询采购模块审核任务待转出转入列表")
    @RequestMapping(value = "/findPurchaseAuditList", method = RequestMethod.POST)
    public Message findPurchaseAuditList(@RequestBody @Valid FindRunTaskListQuery findRunTaskListQuery, BindingResult bindingResult) {

        try {

            if (bindingResult.hasErrors()) {
                for (ObjectError allError : bindingResult.getAllErrors()) {
                    log.error("参数校验:{}", allError.getDefaultMessage());
                    return Message.error(1, allError.getDefaultMessage());
                }
            }

            String transFerType = findRunTaskListQuery.getTransFerType();
            if (StringUtils.isBlank(transFerType)) {// 转出
                IPage<FindRunTaskListQueryVo> selectPage = service.findRunTaskList(findRunTaskListQuery);
                if (selectPage != null) {
                    List<FindRunTaskListQueryVo> records = selectPage.getRecords();
                    for (FindRunTaskListQueryVo record : records) {
                        Map<String, String> map = tbPurchaseApplyMapper.getTransferByDataId(record.getProcessTaskId());
                        if (map != null) {
                            List<Object> list = Lists.newArrayList();
                            list.add(map.get("dept_id"));
                            list.add(map.get("user_id"));
                            record.setUserList(list);
                        }
                    }
                    return Message.success("查询正在运行的任务列表成功", selectPage.getRecords(), selectPage.getTotal());
                }
            }

            if ("1".equals(String.valueOf(transFerType))) {// 转入
                if ("1".equals(findRunTaskListQuery.getType())) { // 采购申请审批
                    Map<String, Object> map = intoList(findRunTaskListQuery.getUserId(), findRunTaskListQuery.getPage(), findRunTaskListQuery.getSize(), 1, "purchase_audit");
                    return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
                } else { // 订单子任务审批
                    Map<String, Object> map = intoList(findRunTaskListQuery.getUserId(), findRunTaskListQuery.getPage(), findRunTaskListQuery.getSize(), 1, "order_audit");
                    return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
                }
            }


            return Message.success("查询正在运行的任务列表成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "查询异常");
        }
    }

    private Map<String, Object> intoList(String userId, Integer page, Integer size, int taskType, String applyType) {
        QueryWrapper<TbTaskTransfer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("model_type", 2);
        queryWrapper.eq("task_type", taskType);
        queryWrapper.eq("receiving_status", 0);//未接收
        queryWrapper.eq("apply_type", applyType);
        IPage<TbTaskTransfer> iPage = new Page<>(page, size);
        IPage<TbTaskTransfer> selectPage = tbTaskTransferService.page(iPage, queryWrapper);
        Map<String, Object> result = Maps.newHashMap();
        if (selectPage != null) {
            List<Object> objects = Lists.newArrayList();
            List<TbTaskTransfer> records = selectPage.getRecords();
            for (TbTaskTransfer record : records) {
                String content = record.getContent();
                System.err.println(content);
                JSONObject jsonObject = JSONObject.parseObject(content);
                jsonObject.put("transferId", record.getId());
                objects.add(jsonObject);
            }
            System.err.println(objects);
            result.put("total", selectPage.getTotal());
            result.put("records", objects);
        }
        return result;
    }

    @ApiOperation(value = "获取所有部门信息", notes = "获取所有部门信息")
    @RequestMapping(value = "/getAllDept", method = RequestMethod.GET)
    public Message getAllDept() {
        List<Map<String, Object>> allDept = tbGlobalUserMapper.getAllDept();
        return Message.success("", allDept);

    }

    @RequestMapping(value = "/getDeptLeader", method = RequestMethod.GET)
    public List<String> getDeptLeader(@RequestParam("deptId") String deptId) {
        return tbGlobalUserService.getDeptLeader(deptId);
    }

    @ApiOperation(value = "开始流程保存", notes = "开始流程保存")
    @RequestMapping(value = "/startProcessSave", method = RequestMethod.POST)
    public Message startProcessSave(@RequestBody TbPurchaseApply data) {
        try {
            data.setAuditStatus("0");
            data.setSubmitStatus(1);
            service.savePurchaseApply(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }


    @ApiOperation(value = "查询采购申请列表", notes = "查询采购申请列表")
    @PostMapping(value = "/findList")
    public Message findList(@RequestBody @Valid PurchaseApplyQuery purchaseApplyQuery, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error("参数校验:{}", allError.getDefaultMessage());
                return Message.error(1, allError.getDefaultMessage());
            }
        }
        IPage<TbPurchaseApply> page = new Page<>(purchaseApplyQuery.getPage(), purchaseApplyQuery.getSize());
        QueryWrapper<TbPurchaseApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by", purchaseApplyQuery.getUserId());
        queryWrapper.like("agent", purchaseApplyQuery.getAgent());
        queryWrapper.like("belong_project", purchaseApplyQuery.getBelongProject());
        queryWrapper.orderByDesc("create_date");
        IPage<TbPurchaseApply> tbPurchaseApplyIPage = service.selectPage(page, queryWrapper);
        return Message.success("成功", tbPurchaseApplyIPage.getRecords(), tbPurchaseApplyIPage.getTotal(), tbPurchaseApplyIPage.getPages());
    }


    /**
     * @author 苏小林
     * @date 2020/5/22 17:39
     * @param: purchaseApplyQuery
     * @param: bindingResult
     * @return: com.xhsj.user.sms.utils.Message
     */
    @ApiOperation(value = "查询审核通过采购申请列表", notes = "查询审核通过采购申请列表")
    @PostMapping(value = "/findListByStatus")
    public Message findListByStatus(@RequestBody @Valid PurchaseApplyQuery purchaseApplyQuery, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error("参数校验:{}", allError.getDefaultMessage());
                return Message.error(1, allError.getDefaultMessage());
            }
        }
        IPage<TbPurchaseApply> page = new Page<>(purchaseApplyQuery.getPage(), purchaseApplyQuery.getSize());
        QueryWrapper<TbPurchaseApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_status", purchaseApplyQuery.getAuditStatus());
        queryWrapper.orderByDesc("create_date");
        IPage<TbPurchaseApply> tbPurchaseApplyIPage = service.selectPage(page, queryWrapper);
        return Message.success("成功", tbPurchaseApplyIPage.getRecords(), tbPurchaseApplyIPage.getTotal(), tbPurchaseApplyIPage.getPages());
    }

    @ApiOperation(value = "获取申购详情列表", notes = "获取申购详情列表")
    @GetMapping(value = "/getPurchaseApplyList")
    //@PreAuthorize("hasAuthority('tb:badges:process:task:view')")
    public Message getPurchaseApplyList(@RequestParam String purchaseApplyId) {
        PurchaseApplyQueryVo purchaseApplyQueryVo = service.getPurchaseApplyList(purchaseApplyId);
        return Message.success("查询历史任务表所有数据成功", purchaseApplyQueryVo);
    }


    @ApiOperation(value = "查询历史任务表所有数据list", notes = "查询历史任务表所有数据list。")
    @RequestMapping(value = "/findHiTaskList", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:process:task:view')")
    public Message findHiTaskList(@RequestBody @Valid FindRunTaskListQuery findRunTaskListQuery, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error("参数校验:{}", allError.getDefaultMessage());
                return Message.error(1, allError.getDefaultMessage());
            }
        }
        IPage<FindHiTaskListVo> selectPage = service.findHiTaskList(findRunTaskListQuery);
        return Message.success("查询历史任务表所有数据成功", selectPage.getRecords(), selectPage.getTotal());
    }

    @ApiOperation(value = "查询正在运行的任务列表", notes = "查询正在运行的任务列表")
    @RequestMapping(value = "/findRunTaskList", method = RequestMethod.POST)
    public Message findRunTaskList(@RequestBody @Valid FindRunTaskListQuery findRunTaskListQuery, BindingResult bindingResult) {
        try {

            if (bindingResult.hasErrors()) {
                for (ObjectError allError : bindingResult.getAllErrors()) {
                    log.error("参数校验:{}", allError.getDefaultMessage());
                    return Message.error(1, allError.getDefaultMessage());
                }
            }

            IPage<FindRunTaskListQueryVo> selectPage = service.findRunTaskList(findRunTaskListQuery);
            if (selectPage != null) {
                return Message.success("查询正在运行的任务列表成功", selectPage.getRecords(), selectPage.getTotal());
            }
            return Message.success("查询正在运行的任务列表成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "查询异常");
        }
    }

    //进度总览
    @ApiOperation(value = "进度总览", notes = "进度总览")
    @GetMapping(value = "/progressOverviewList")
    public Message progressOverviewList(@RequestParam(value = "processType") String processType,
                                        @RequestParam(value = "category") int category,
                                        @RequestParam(value = "dataId",required = false) String dataId) {
        try {
            List<ProgressOverviewListQueryVo> progressOverviewListQueryVos = service.progressOverviewList(processType, category);
            Integer nodeNum = null;
            if (StringUtils.isNotBlank(dataId)) {
                nodeNum = service.getNodeNum(dataId);
                if (nodeNum == null) {
                    nodeNum = 0;
                }
            }

            Map<String, Object> map = Maps.newHashMap();
            map.put("nodeNum",nodeNum);
            map.put("data",progressOverviewListQueryVos);

            return Message.success("进度总览成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "进度总览查询异常");
        }
    }


    /**
     * @param dataId 当前业务id
     * @return
     */
    @ApiOperation(value = "进度通知", notes = "进度通知")
    @GetMapping(value = "/progressNoticeListAll")
    public Message progressNoticeListAll(@RequestParam(value = "dataId") String dataId) {
        try {
            log.info("进度通知参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            List list = new ArrayList();
            list.add("0");
            list.add("1");
            list.add("2");
            List nodeList = new ArrayList();
            list.add("0");
            list.add("1");
            list.add("2");
//			tbPurchaseOrderFileService.getPurchaseOrderFileList(dataId,list,nodeList);
//			tbPurchaseOrderPaymentApplyService.getPayMentApplyList(dataId);

            return Message.success("进度通知成功", tbPurchaseSubtaskQualityRecordService.getOrderQualityRecordList(dataId));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "进度通知查询异常");
        }
    }

    @ApiOperation(value = "获取报检单", notes = "获取报检单")
    @GetMapping(value = "/getInspectionApplicationFileList")
    public Message getInspectionApplicationFileList(@RequestParam(value = "dataId") String dataId,
                                                    @RequestParam(value = "purchaseTaskId") String purchaseTaskId) {
        try {
            log.info("获取报检单参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            List<String> typeList = new ArrayList<>();
            typeList.add("0");
            List<String> nodeList = new ArrayList<>();
            return Message.success("获取报检单成功", tbPurchaseSubtaskOtherFileService.getInspectionApplicationFileList(dataId, typeList, nodeList, purchaseTaskId));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "获取报检单查询异常");
        }
    }

    @ApiOperation(value = "获取支付凭证", notes = "获取支付凭证")
    @GetMapping(value = "/getPayMentFileList")
    public Message getPayMentFileList(@RequestParam(value = "dataId") String dataId) {
        try {
            log.info("低值固资获取支付凭证参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            List<String> typeList = new ArrayList<>();
            typeList.add("4");
            List<String> nodeList = new ArrayList<>();
//				nodeList.add(nodeId);
            return Message.success("低值固资获取支付凭证成功", tbPurchaseSubtaskOtherFileService.getPurchaseOrderOtherFileList(dataId, typeList, nodeList));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "获取支付凭证查询异常");
        }
    }


    @ApiOperation(value = "获取支付凭证-供财务上传支付凭证使用", notes = "获取支付凭证-供财务上传支付凭证使用")
    @GetMapping(value = "/getPayMentFile")
    public Message getPayMentFile(@RequestParam(value = "dataId") String dataId,@RequestParam(value = "createBy") String createBy) {
        try {
            log.info("低值固资获取支付凭证参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }

            List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(Long.parseLong(createBy));
            if (roleNames.contains(teller)) {// 如果是出纳
                List<Object> list = Lists.newArrayList();
                return Message.success("低值固资获取支付凭证成功",list);

            } else {
                List<String> typeList = new ArrayList<>();
                typeList.add("4");
                List<String> nodeList = new ArrayList<>();
                List<Map<String, Object>> list = tbPurchaseSubtaskOtherFileService.getPurchaseOrderOtherFileList(dataId, typeList, nodeList);
                if (list !=null && list.size() > 0) {
                    Map<String, Object> map = list.get(list.size() - 1);
                    return Message.success("低值固资获取支付凭证成功", Arrays.asList(map));
                }
                return Message.success("低值固资获取支付凭证成功", Arrays.asList());

            }


        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "获取支付凭证查询异常");
        }
    }

    @ApiOperation(value = "获取质检记录", notes = "获取质检记录")
    @GetMapping(value = "/getOrderQualityRecordList")
    public Message getOrderQualityRecordList(@RequestParam(value = "dataId") String dataId) {
        try {
            log.info("获取质检记录参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            return Message.success("获取质检记录成功", tbPurchaseSubtaskQualityRecordService.getOrderQualityRecordList(dataId));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "获取质检记录查询异常");
        }
    }


    @ApiOperation(value = "获取质检记录良品，特采，退货数量", notes = "获取质检记录良品，特采，退货数量")
    @GetMapping(value = "/getOrderQualityRecordNumList")
    public Message getOrderQualityRecordNumList(@RequestParam(value = "dataId") String dataId, @RequestParam(value = "type") int type) {
        try {
            log.info("获取质检记录参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            return Message.success("获取质检记录良品，特采，退货数量", tbPurchaseSubtaskQualityRecordService.getOrderQualityRecordNumList(dataId, type));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "获取质检记录良品，特采，退货数量查询异常");
        }
    }

    @ApiOperation(value = "进度通知", notes = "进度通知")
    @GetMapping(value = "/progressNoticeList")
    public Message progressNoticeList(@RequestParam(value = "dataId") String dataId) {
        try {
            log.info("进度通知参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            return Message.success("进度通知成功", service.progressNoticeList(dataId));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "进度通知查询异常");
        }
    }

    @ApiOperation(value = "支付申请记录", notes = "支付申请记录")
    @GetMapping(value = "/payMentApplyList")
    public Message payMentApplyList(@RequestParam(value = "dataId") String dataId, @RequestParam(value = "batch") String batch) {
        try {
            log.info("支付申请记录参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            List<String> batchList = Arrays.asList(batch.split(","));
            return Message.success("成功", tbPurchaseSubtaskPaymentApplyService.getPayMentApplyList(dataId, batchList));
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "审批记录查询异常");
        }
    }

//	@ApiOperation(value = "自动生成编号", notes = "自动生成编号")
//	@GetMapping(value="/getAutoNumber")
//	public Message getAutoNumber(@RequestParam(value="type") String type,@RequestParam(value="dept") String dept) {
//		try {
//			log.info("自动生成编号参数{}",type);
//			if(StringUtils.isBlank(type)){
//				return Message.error(1,"type类型参数不能为空");
//			}
//
//
//           //日期
//			Date date =new Date();
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
//			String time=sdf.format(date);
//			//类别 低值 L   固资F  项目P
//			//工单
//			//自增
//			//部门
//            Object deptCode = redisTemplate.opsForValue().get("dept");
//            String number="xhsj"+deptCode;
//			if("1".equals(type)){//采购申请
//				//获取最新的采购申请编号  A
//				String num = service.getApplyNewNum();
//		 }else if("2".equals(type)){//订单任务
//				//获取最新的订单任务编号 O
//				String num = service.getOrderNewNum();
//		 }else if("3".equals(type)){//订单任务子任务
//				//获取最新的订单任务子任务编号 S
//				String num = service.getOrderSubtaskNewNum();
//		 }
//		 return Message.success("成功");
//		}catch (Exception e){
//			e.printStackTrace();
//			return Message.error(1,"审批记录查询异常");
//		}
//	}


    @ApiOperation(value = "保存部门代号", notes = "保存部门代号")
    @GetMapping(value = "/saveDepartmentCode")
    public Message saveDepartmentCode(@RequestParam(value = "deptId") String deptId, @RequestParam(value = "deptCode") String deptCode) {
        try {
            redisTemplate.opsForValue().set("deptCode:" + deptId, deptCode);
            return Message.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "审批记录查询异常");
        }
    }


    @ApiOperation(value = "部门代号", notes = "保存部门代号")
    @GetMapping(value = "/departmentCode")
    public void departmentCode() {
        List<Map<String, Object>> allDept = tbGlobalUserMapper.getAllDept();
        for (Map<String, Object> dept : allDept
        ) {
            if ("总经理办公室".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "zb");
            } else if ("综合管理部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "zg");
            } else if ("技术研发部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "yf");
            } else if ("软件部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "rj");
            } else if ("视频部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "sp");
            } else if ("财务部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "cw");
            } else if ("知识产权部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "cq");
            } else if ("供应链管理部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "cg");
            } else if ("品质管理部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "pz");
            } else if ("战略及市场营销部".equals(dept.get("label"))) {
                redisTemplate.opsForValue().set("deptCode:" + dept.get("value"), "yx");
            }
        }

    }

    @ApiOperation(value = "审批记录", notes = "审批记录")
    @GetMapping(value = "/approvalRecordList")
    public Message approvalRecordList(@RequestParam(value = "dataId") String dataId,
                                      @RequestParam(value = "processType") int processType,
                                      @RequestParam(value = "page") int page,
                                      @RequestParam(value = "size") int size) {
        try {
            int pageNum = 1;
            int pageSize = 20;
            if (StringUtils.isNotNull(page)) {
                pageNum = page;
            }
            if (StringUtils.isNotNull(size)) {
                pageSize = size;
            }
            log.info("审批记录业务id参数{}", dataId);
            if (StringUtils.isBlank(dataId)) {
                return Message.error(1, "dataId 当前业务id参数不能为空");
            }
            IPage<ApprovalRecordListQueryVo> iPage = service.approvalRecordList(dataId, processType, pageNum, pageSize);
            return Message.success("审批记录成功", iPage.getRecords(), iPage.getTotal(), iPage.getPages());
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "审批记录查询异常");
        }
    }

    @ApiOperation(value = "供应链得成员", notes = "供应链得成员")
    @GetMapping(value = "/getMemberList")
    public Message getMemberList() {
        try {
            List<String> roleKeynameList = Arrays.asList(purchaseSpecialist.split(","));
            Set<Map<String, Object>> approvalRecordList = service.getMemberList("供应链管理部", roleKeynameList);
            return Message.success("审批记录成功", approvalRecordList);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "审批记录查询异常");
        }
    }

    @ApiOperation(value = "物料不良记录", notes = "物料不良记录")
    @GetMapping(value = "/getBadMaterialRecord")
    public Message getBadMaterialRecord(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> approvalRecordList = service.getBadMaterialRecord(dataId);
            return Message.success("物料不良记录", approvalRecordList);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "物料不良记录查询异常");
        }
    }

    //正在执行的合同审批
    @ApiOperation(value = "正在执行的合同审批", notes = "正在执行的合同审批")
    @RequestMapping(value = "/getContractExcelFlowList", method = RequestMethod.GET)
    public Message getContractExcelFlowList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseProcessTaskService.getContractExcelFlowList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }

    //获取商品信息
    @ApiOperation(value = "获取子任务清单信息", notes = "获取子任务清单信息")
    @RequestMapping(value = "/getGoodsList", method = RequestMethod.GET)
    public Message getGoodsList(@RequestParam String dataId) {
        try {
//			List<Map<String, Object>> statementList =tbPurchaseOrderGoodsService.getGoodsList(dataId);
            List<Map<String, Object>> statementList = tbPurchaseSubtaskListService.getSubtaskList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("获取子任务清单信息失败:{}", e);
            return Message.error(1, "获取子任务清单信息失败");
        }
    }


    //获取待入库数量
    @ApiOperation(value = "获取待入库数量", notes = "获取待入库数量")
    @RequestMapping(value = "/getWarehousingNumberList", method = RequestMethod.GET)
    public Message getWarehousingNumberList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseSubtaskQualityRecordService.getWarehousingNumberList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }

    //获取商品信息
    @ApiOperation(value = "获取订单子任务清单信息", notes = "获取订单子任务清单信息")
    @RequestMapping(value = "/getSubtaskList", method = RequestMethod.GET)
    public Message getSubtaskList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseSubtaskListService.getSubtaskList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }

    //获取归口部门意见
    @ApiOperation(value = "获取归口部门意见", notes = "获取归口部门意见")
    @RequestMapping(value = "/getDeptLeaderOpinon", method = RequestMethod.GET)
    public Message getDeptLeaderOpinon(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseProcessOpinionService.getDeptLeaderOpinon(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }


    //获取 入库单
    @ApiOperation(value = "获取 入库单", notes = "获取 入库单")
    @RequestMapping(value = "/getReceiptList", method = RequestMethod.GET)
    public Message getReceiptList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseSubtaskStorageRecordFileService.getReceiptList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }


    //获取终止合同申请相关数据
    @ApiOperation(value = "获取终止合同申请相关数据", notes = "获取终止合同申请相关数据")
    @RequestMapping(value = "/getTerminationContractList", method = RequestMethod.GET)
    public Message getTerminationContractList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseTerminationContractApplyFileService.getTerminationContractList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, "保存失败");
        }
    }

    @ApiOperation(value = "入库时质检记录", notes = "入库时质检记录")
    @RequestMapping(value = "/getWarehousingQualityRecordList", method = RequestMethod.GET)
    public Message getWarehousingQualityRecordList(@RequestParam String dataId) {
        try {
            List<Map<String, Object>> statementList = tbPurchaseSubtaskQualityRecordService.getWarehousingQualityRecordList(dataId);
            return Message.success("成功", statementList);
        } catch (Exception e) {
            log.error("获取入库时质检记录失败:{}", e);
            return Message.error(1, "获取入库时质检记录失败");
        }
    }


    @ApiOperation(value = "供应链代办数", notes = "供应链代办数")
    @RequestMapping(value = "/purchaseAgencyNum", method = RequestMethod.GET)
    public Message purchaseAgencyNum(@RequestParam Integer userId) {
        try {
            return Message.success("成功", tbPurchaseProcessTaskService.purchaseAgencyNum(userId));
        } catch (Exception e) {
            log.error("供应链代办数失败:{}", e);
            return Message.error(1, "供应链代办数失败");
        }
    }

    @ApiOperation(value = "获取所有用户列表", notes = "获取所有用户列表")
    @RequestMapping(value = "/findAllUser", method = RequestMethod.GET)
    public Message findAllUser() {
        try {
//            departmentId
            List<Map<String, Object>> allDept = tbGlobalUserMapper.getAllDept();
            List<Map<String, String>> allUser = tbGlobalUserMapper.getAllUser();
            for (Map<String, Object> map : allDept) {
                Object value = map.get("value");
                List<Map<String, String>> ll = allUser.stream().filter(m -> {
                    Integer departmentId = StringUtils.toInteger(m.get("departmentId"));
                    boolean b = departmentId.equals(StringUtils.toInteger(value));
                    return b;
                }).collect(Collectors.toList());
                map.put("children", ll);
            }
            return Message.success("成功", allDept);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error();
        }
    }


}

